package com.yq.ylmall.service;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.util.IdUtil;
import com.yq.ylmall.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
@RequiredArgsConstructor
public class MinioService {

    private final MinioConfig prop;
    private final MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.warn("Minio服务 ===> 获取存储桶异常，错误信息：{}", e.getMessage());
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     *
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.warn("Minio服务 ===> 创建存储桶异常，错误信息：{}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.warn("Minio服务 ===> 删除存储桶异常，错误信息：{}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileName = IdUtil.fastSimpleUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date()) + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(prop.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            log.warn("文件上传异常，文件名：{}，存储位置：{}\n错误信息：{}", file.getOriginalFilename(), objectName, e.getMessage());
            return null;
        }
        return prop.getEndpoint() + prop.getBucketName() + objectName;
    }

    /**
     * 获取预览图片地址
     *
     * @param fileName
     * @return
     */
    public String preview(String fileName) {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(prop.getBucketName()).object(fileName).method(Method.GET).build();
        try {
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            log.warn("Minio服务 ===> 获取预览地址异常，错误信息：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(prop.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                while ((len = response.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            log.warn("文件上传异常，文件名：{}\n错误信息：{}", fileName, e.getMessage());
        }
    }

    /**
     * 删除图片
     *
     * @param filepath 文件访问路径
     * @return boolean
     */
    public boolean remove(String filepath) {
        String filename = null;
        try {
            filename = filepath.substring(prop.getEndpoint().length() + prop.getBucketName().length() + 1);
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(prop.getBucketName()).object(filename).build());
        } catch (Exception e) {
            log.warn("Minio服务 ===> 文件删除异常，文件名：{}，错误信息：{}", filename, e.getMessage());
            return false;
        }
        return true;
    }

}
